import type { ObjectDirective, DirectiveBinding } from 'vue'

const emptyBoxClassName = 'contain-empty-box'

const emptyBoxStyles = {
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  display: 'flex',
  'justify-content': 'center',
  'align-items': 'center',
  'flex-direction': 'column',
  'z-index': 999
}

const empty: ObjectDirective = {
  mounted (el: HTMLDivElement, binding: DirectiveBinding) {
    if (binding.value && el) {
      renderEmptyElement(el)
    }
  },

  updated (el: HTMLDivElement, binding: DirectiveBinding) {
    if (binding.value && el) {
      renderEmptyElement(el)
    } else if (!binding.value) {
      const emptyDom = el.querySelector(`.${emptyBoxClassName}`)
      emptyDom?.remove()
      el.classList.remove('el-loading-parent--relative')
    }
  }
}

function renderEmptyElement (el) {
  const emptyTextTip = el.getAttribute('empty-text')
  el.classList.add('el-loading-parent--relative')
  const prevEmptyDom = el.querySelector(`.${emptyBoxClassName}`)
  prevEmptyDom?.remove()
  const emptyDom = document.createElement('div')
  emptyDom.className = emptyBoxClassName
  for (const key in emptyBoxStyles) {
    emptyDom.style[key] = emptyBoxStyles[key]
  }
  const emptyText = document.createElement('p')
  emptyText.innerText = emptyTextTip || '暂无数据'
  emptyText.style.fontSize = '14px'
  emptyText.style.color = '#999'
  emptyText.style.textAlign = 'center'
  emptyDom.appendChild(emptyText)
  el.appendChild(emptyDom)
}

export default empty
